package com.moli.iov.down.command.codec.decode.decoders;

import com.moli.iov.down.command.codec.decode.bean.SettingBean;
import com.moli.iov.down.command.codec.decode.bean.extend.SettingExtendBean;
import com.moli.iov.util.StringUtil;
import org.apache.commons.lang.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  终端参数设置结果应答 解码
 * </p>
 *
 * @author: zql
 * @Date: 2018/11/30 19:09
 */
@Component("settingDecoder")
@Scope("prototype")
public class SettingDecoder extends BaseDecoder{

    protected final Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * 参数设置结果默认长度 3 个字节
     */
    private static final int SETTING_EXTEND_DATA_DEFAULT_LENGTH = 3;

    public SettingBean decode(byte[] data){
        try{
            log.info("终端参数设置结果应答 解码 入参：{}", data);
            byte[] date = ArrayUtils.subarray(data, 0, 6);
            data = ArrayUtils.subarray(data, 6, data.length);

            byte[] serialNumber = ArrayUtils.subarray(data, 0, 2);
            data = ArrayUtils.subarray(data, 2, data.length);
            List<SettingExtendBean> settingExtendBeans = this.extendDecode(data);

            SettingBean settingBean = new SettingBean();
            settingBean.setDate(this.dateDecode(date));
            settingBean.setSerialNumber(this.serialNumberDecode(serialNumber));
            settingBean.setSettingExtendBeans(settingExtendBeans);

            log.info("终端参数设置结果应答 解码 结果: {}", settingBean);
            return settingBean;
        }catch(Exception e){
            log.error("终端参数设置结果应答 解析 异常", e);
            return null;
        }
    }

    public List<SettingExtendBean> extendDecode(byte[] data){
        List<SettingExtendBean> settingExtendBeans = new ArrayList<>();
        for(int i = 0; i <= data.length / SETTING_EXTEND_DATA_DEFAULT_LENGTH; i++){
            byte[] paramId = ArrayUtils.subarray(data, 0, 2);
            data = ArrayUtils.subarray(data, 2, data.length);

            byte[] result = ArrayUtils.subarray(data, 0, 1);
            data = ArrayUtils.subarray(data, 1, data.length);
            SettingExtendBean settingExtendBean = new SettingExtendBean();
            settingExtendBean.setParamId(StringUtil.bytesToHexString(paramId));
            settingExtendBean.setResult(result[0]);
            settingExtendBeans.add(settingExtendBean);
        }
        return settingExtendBeans;
    }
}
